package thread;

import mario.Mario;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class MyGamFrame extends JFrame implements KeyListener, Runnable {
    StaticValue mmp = new StaticValue();
    private Mario mario = new Mario();
    private Thread thread = new Thread(this);
    //    用于双缓存
    private Image offScreenImage = null;
    public MyGamFrame() {
        //https://zhidao.baidu.com/question/488845793.html
        //        设置窗口大小
        this.setSize(800, 600);
//        设置窗口居中显示
        this.setLocationRelativeTo(null);
//        设置窗口的可见性
        this.setVisible(true);
//        设置点击窗口的关闭键，结束程序
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//        设置窗口大小不可变
        this.setResizable(false);
//        向窗口对象添加键盘监听器；
        this.addKeyListener(this);
//        设置窗口名称
        this.setTitle("游戏基础骨架");
//        初始化资源素材
        mmp.init();
        mario = new Mario(10, 355);
        thread.start();

    }

    //键入的键盘类型
    @Override
    public void keyTyped(KeyEvent e) {

    }

    //什么按键被触发
    @Override
    public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == 39) {
            mario.rightMove();
        }
        if (e.getKeyCode() == 37) {
            mario.leftMove();
        }
    }

    //按键释放
    @Override
    public void keyReleased(KeyEvent e) {
        if (e.getKeyCode() == 39) {
            mario.rightStop();
        }
        if (e.getKeyCode() == 37) {
            mario.leftStop();
        }
    }

    @Override
    public void paint(Graphics g) {
        if (offScreenImage == null) {
            offScreenImage = createImage(800, 600);
        }
        Graphics graphics = offScreenImage.getGraphics();
        graphics.fillRect(0, 0, 800, 600);
        graphics.drawImage(mario.getShow(), mario.getX(), mario.getY(), this);
        g.drawImage(offScreenImage, 0, 0, this);
    }

    @Override
    public void run() {
        try {
            while (true) {
                Thread.sleep(50);
                repaint();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        MyGamFrame myFrame = new MyGamFrame();
    }
}
